package com.seeyon.apps.ddkk.manager;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.sql.SQLException;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import www.seeyon.com.utils.StringUtil;

import com.seeyon.apps.addressbook.manager.AddressBookCustomerFieldInfoManager;
import com.seeyon.apps.addressbook.manager.AddressBookManager;
import com.seeyon.apps.addressbook.po.AddressBook;
import com.seeyon.apps.collaboration.manager.ColManager;
import com.seeyon.apps.ddkk.dao.QiangsDao;
import com.seeyon.apps.kk.constants.Constants;
import com.seeyon.apps.kk.dao.SyncOrgDao;
import com.seeyon.apps.kk.manager.FormDataBaseManager;
import com.seeyon.apps.kk.manager.FreemarkFlowManager;
import com.seeyon.apps.kk.util.HeheHttpUtil;
import com.seeyon.apps.kk.util.RandomCode;
import com.seeyon.apps.kk.util.RestUtil;
import com.seeyon.apps.mplus.secure.sync.MemberSync;
import com.seeyon.cap4.form.api.FormApi4Cap4;
import com.seeyon.cap4.form.bean.FormBean;
import com.seeyon.cap4.form.bean.FormDataMasterBean;
import com.seeyon.cap4.form.bean.FormDataSubBean;
import com.seeyon.cap4.form.bean.FormFieldBean;
import com.seeyon.cap4.form.bean.FormRelationshipBean;
import com.seeyon.cap4.form.bean.FormRelationshipMapBean;
import com.seeyon.cap4.form.bean.FormTableBean;
import com.seeyon.cap4.form.modules.engin.businessRelation.CAP4FormBusinessRelationDAO;
import com.seeyon.cap4.form.modules.engin.businessRelation.CAP4FormBusinessRelationManager;
import com.seeyon.cap4.form.modules.engin.relation.CAP4FormRelationRecordDAO;
import com.seeyon.cap4.form.po.CAPFormRelationRecord;
import com.seeyon.ctp.common.AppContext;
import com.seeyon.ctp.common.SystemEnvironment;
import com.seeyon.ctp.common.affair.manager.AffairManager;
import com.seeyon.ctp.common.config.manager.ConfigManager;
import com.seeyon.ctp.common.content.affair.constants.StateEnum;
import com.seeyon.ctp.common.ctpenumnew.manager.EnumManager;
import com.seeyon.ctp.common.exceptions.BusinessException;
import com.seeyon.ctp.common.metadata.bo.MetadataColumnBO;
import com.seeyon.ctp.common.po.content.CtpContentAll;
import com.seeyon.ctp.common.po.ctpenumnew.CtpEnumBean;
import com.seeyon.ctp.common.po.ctpenumnew.CtpEnumItem;
import com.seeyon.ctp.organization.bo.V3xOrgDepartment;
import com.seeyon.ctp.organization.bo.V3xOrgMember;
import com.seeyon.ctp.organization.manager.OrgManager;
import com.seeyon.ctp.organization.manager.OrgManagerDirect;
import com.seeyon.ctp.usersystem.manager.RestUserManager;
import com.seeyon.ctp.util.DBAgent;
import com.seeyon.ctp.util.DateUtil;
import com.seeyon.ctp.util.Datetimes;
import com.seeyon.ctp.util.FlipInfo;
import com.seeyon.ctp.util.ParamUtil;
import com.seeyon.ctp.util.Strings;
import com.seeyon.ctp.util.annotation.AjaxAccess;
import com.seeyon.ctp.util.json.JSONUtil;
import com.seeyon.v3x.mail.manager.MessageMailManager;
import com.seeyon.v3x.worktimeset.manager.WorkTimeManager;

public class QiangsDDManagerImpl implements QiangsDDManager {

    private static final Log log = LogFactory.getLog(QiangsDDManagerImpl.class);
    private QiangsDao qiangsDao;
    private SyncOrgDao baseQiangsDao;
    private OrgManager orgManager;
    private FormApi4Cap4 formApi4Cap4;
    private KkqxbManager kkqxbManager;
    private OrgManagerDirect orgManagerDirect;
    private FreemarkFlowManager kkFlowManager;
    private DDKkDistributorManger kkDistributor;
    private MessageMailManager messageMailManager;
    private FormDataBaseManager kkBaseFormManager;
    private CAP4FormRelationRecordDAO cap4FormRelationRecordDAO;
    private CAP4FormBusinessRelationManager cap4FormBusinessRelationManager;

    public void setQiangsDao(QiangsDao qiangsDao) {
		this.qiangsDao = qiangsDao;
	}

	public void setBaseQiangsDao(SyncOrgDao baseQiangsDao) {
		this.baseQiangsDao = baseQiangsDao;
	}

	public void setOrgManager(OrgManager orgManager) {
		this.orgManager = orgManager;
	}

	public void setFormApi4Cap4(FormApi4Cap4 formApi4Cap4) {
		this.formApi4Cap4 = formApi4Cap4;
	}

	public void setKkqxbManager(KkqxbManager kkqxbManager) {
		this.kkqxbManager = kkqxbManager;
	}

	public void setOrgManagerDirect(OrgManagerDirect orgManagerDirect) {
		this.orgManagerDirect = orgManagerDirect;
	}

	public void setKkFlowManager(FreemarkFlowManager kkFlowManager) {
		this.kkFlowManager = kkFlowManager;
	}

	public void setKkDistributor(DDKkDistributorManger kkDistributor) {
		this.kkDistributor = kkDistributor;
	}

	public void setMessageMailManager(MessageMailManager messageMailManager) {
		this.messageMailManager = messageMailManager;
	}

	public void setKkBaseFormManager(FormDataBaseManager kkBaseFormManager) {
		this.kkBaseFormManager = kkBaseFormManager;
	}

	public void setCap4FormRelationRecordDAO(
			CAP4FormRelationRecordDAO cap4FormRelationRecordDAO) {
		this.cap4FormRelationRecordDAO = cap4FormRelationRecordDAO;
	}

	public void setCap4FormBusinessRelationManager(
			CAP4FormBusinessRelationManager cap4FormBusinessRelationManager) {
		this.cap4FormBusinessRelationManager = cap4FormBusinessRelationManager;
	}
	

	@Override
    public void createFormRelation(FormBean sourceBean, FormDataMasterBean sourceDataBean, String targetCode, Long targetMasterId) throws BusinessException, SQLException {
        FormBean targetBean = formApi4Cap4.getFormByFormCode(targetCode);
        FormDataMasterBean targetDataBean = formApi4Cap4.findDataById(targetMasterId, targetBean, null);
        List<FormRelationshipBean> beanList = cap4FormBusinessRelationManager.getFormRelationshipListByFormId(
                sourceBean.getId(), targetBean.getId(), "between");
        for (FormRelationshipBean bean : beanList) {
            List<FormRelationshipMapBean> mapList = bean.getRelationMapList();
            for (FormRelationshipMapBean mapBean : mapList) {
                boolean isRelation = false;
                List<Map<String, String>> fieldList = mapBean.getRelationFieldMap();
                Map<String, Object> subDataMap = new HashMap<String, Object>();

                for (Map<String, String> fieldMap : fieldList) {
                    Set<String> keys = fieldMap.keySet();
                    for (String key : keys) {
                        Object value = targetDataBean.getFieldValue(fieldMap.get(key));
                        if (sourceBean.getFieldBeanByName(key).isMasterField()) {
//								if(bean.getTargetTable().equals(targetBean.getMasterTableBean().getTableName())){
                            sourceDataBean.addFieldValue(key, value);
                            isRelation = true;
//								}
                        } else {
                            List<FormTableBean> subBeanList = sourceBean.getSubTableBean();
                            for (FormTableBean subSourceBean : subBeanList) {
                                if (null != subSourceBean.getFieldBeanByName(key)) {
//											&& bean.getTargetTable().equals(subSourceBean.getTableName())){
                                    subDataMap.put("subFormTableBean", subSourceBean);
                                    isRelation = true;
                                    break;
                                }
                            }
                            subDataMap.put(key, value);
                        }
                    }
                }
                if (isRelation) {
                    CAPFormRelationRecord recordPo = new CAPFormRelationRecord();
                    if (!subDataMap.isEmpty()) {
                        FormTableBean subSourceBean = (FormTableBean) subDataMap.get("subFormTableBean");
                        subDataMap.remove("subFormTableBean");
                        FormDataSubBean formDataSubBean
                                = new FormDataSubBean(subDataMap, subSourceBean, sourceDataBean, true);
                        sourceDataBean.addSubData(subSourceBean.getTableName(), formDataSubBean);
                        recordPo.setFromSubdataId(formDataSubBean.getId());
                    }
                    recordPo.setIdIfNew();
                    recordPo.setFromMasterDataId(sourceDataBean.getId());
                    recordPo.setToMasterDataId(targetMasterId);
                    recordPo.setFieldName(mapBean.getSelectedField());
                    if (1 == targetBean.getFormType()) {
                        recordPo.setFormType(1);
                    } else {
                        recordPo.setFormType(42);
                    }
                    recordPo.setType(1);
                    recordPo.setMemberId(AppContext.currentUserId());
                    recordPo.setFromFormId(sourceBean.getId());
                    recordPo.setToFormId(targetBean.getId());
                    recordPo.setRelationShipId(bean.getId());
                    recordPo.setViewThrough(1);

                    Map dataInfo = new HashMap();
                    dataInfo.put("pcView", mapBean.getPcView());
                    dataInfo.put("phoneView", mapBean.getPhoneView());
                    recordPo.setDataInfo(JSONUtil.toJSONString(dataInfo));
                    final CAPFormRelationRecord finalOpbj = recordPo;
                    Thread thread = new Thread(new Runnable() {

                        @Override
                        public void run() {
                            // TODO Auto-generated method stub
                            try {
                                Thread.sleep(30 * 1000L);
                                cap4FormRelationRecordDAO.insertCAPFormRelationRecord(finalOpbj);
                            } catch (BusinessException e) {
                                // TODO Auto-generated catch block
                                log.error("##强生客开: ", e);
                            } catch (InterruptedException e) {
                                // TODO Auto-generated catch block
                                log.error("##强生客开: ", e);
                            }
                        }
                    });
                    thread.start();
                }
            }
        }
    }

    @AjaxAccess
    public String updateKeyMemberInfo(int type, String masterId, String name, String formId) {
        try {
            FormBean formBean = formApi4Cap4.getForm(Long.valueOf(formId));
            FormBean keyBean = formApi4Cap4.getFormByFormCode(Constants.keyMemberCode);
            FormDataMasterBean dataMasterBean = formApi4Cap4.findDataById(Long.valueOf(masterId),
                    formBean, null);
            Long targetId = null;
            if (type == 0) {
                targetId = Long.valueOf(dataMasterBean.getFieldValue(formBean.getFieldBeanByDisplay("公司负责人底表ID").getName()).toString());
            } else if (type == 1) {
                targetId = Long.valueOf(dataMasterBean.getFieldValue(formBean.getFieldBeanByDisplay("业务负责人底表ID").getName()).toString());
            } else if (type == 2) {
                targetId = Long.valueOf(dataMasterBean.getFieldValue(formBean.getFieldBeanByDisplay("医疗器械许可人底表ID").getName()).toString());
            } else {
                return "0";
            }
            FormDataMasterBean keyDataMasterBean = formApi4Cap4.findDataById(targetId,
                    keyBean, null);
            Map<String, Object> param = new HashMap<String, Object>();
            param.put("姓名", name.trim());
            kkBaseFormManager.updateFormData(Constants.keyMemberCode, keyDataMasterBean, param);
			/*Map<Long, FormDataMasterBean> map = findRelationKeyMember(formBean, dataMasterBean);
			for(Long subId: map.keySet()){
				if(map.get(subId).getId().equals(targetId)){
					for(FormTableBean subTable :formBean.getSubTableBean()){
						if(subTable.getDisplay().contains("关键人员简历")){
							for(FormDataSubBean subDataBean :dataMasterBean.getSubData(subTable.getTableName())){
								if(subDataBean.getId().equals(subId)){
									subDataBean.addFieldValue(formBean.getFieldBeanByDisplay("关键人员简历姓名").getName(), name);
									formApi4Cap4.saveOrUpdateFormData(dataMasterBean, formBean.getId(), true);
									break;
								}
							}
							break;
						}
					}
					break;
				}
			}*/
            return targetId.toString();
        } catch (BusinessException e) {
            // TODO Auto-generated catch block
            log.error("##强生客开: ", e);
        } catch (NumberFormatException e) {
            // TODO Auto-generated catch block
            log.error("##强生客开: ", e);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            log.error("##强生客开: ", e);
        }
        return "0";
    }

    @Override
    public void dealFormNode() {
        try {
            FormBean formBean = formApi4Cap4.getFormByFormCode(Constants.ddApplyCode);
            FormBean renewBean = formApi4Cap4.getFormByFormCode(Constants.ddRenew);

            FormBean ddBean = formApi4Cap4.getFormByFormCode(Constants.ddBaseCode);
            FormBean letterBean = formApi4Cap4.getFormByFormCode(Constants.letterCode);
            V3xOrgMember member = orgManager.getMemberByLoginName(Constants.createUser);
            List<Long> formIds = new ArrayList<Long>();
            formIds.add(formBean.getId());
            formIds.add(renewBean.getId());

            List<Map> affairList = qiangsDao.getAffairListByMemberIdAndState(member.getId(), formIds, StateEnum.col_pending);
            log.info("##强生客开: 获取待办事项共  " + affairList.size() + " 项.");
            for (Map params : affairList) {
                try {
                    Long affairId = ParamUtil.getLong(params, "id");
                    String subject = ParamUtil.getString(params, "subject");
                    Long formId = ParamUtil.getLong(params, "form_app_id");
                    Long masterId = ParamUtil.getLong(params, "form_recordid");
                    log.info("##强生客开: 获取待办事项参数:  affairId=" + affairId + "   formId=" + formId + "  masterId=" + masterId);
                    String content = null;
                    FormDataMasterBean dataMaster = null;
                    boolean firstUpdate = false;
                    boolean lastUpdate = false;
                    log.info("##强生客开: 自动处理 《" + subject + "》****start，formBean.getId：" + formBean.getId() + ",formId:" + formId);
                    /***  DD审批流程自动处理   */
                    if (formBean.getId().equals(formId)) {
                        dataMaster = formApi4Cap4.getDataMasterBeanById(masterId, formBean, null);
                        String compliance = dataMaster.getFieldValue(formBean.getFieldBeanByDisplay("合规状态").getName()) == null
                                ? "" : dataMaster.getFieldValue(formBean.getFieldBeanByDisplay("合规状态").getName()).toString();
                        String state = dataMaster.getFieldValue(formBean.getFieldBeanByDisplay("承诺函状态").getName()) == null
                                ? "" : dataMaster.getFieldValue(formBean.getFieldBeanByDisplay("承诺函状态").getName()).toString();
                        String name = dataMaster.getFieldValue(formBean.getFieldBeanByDisplay("经销商名称").getName()).toString();
                        log.info("compliance：" + compliance + ",isEmpty:" + Strings.isEmpty(compliance));
                        /******合规问题节点校验*******/
                        if (Strings.isEmpty(compliance)) {
                            FormBean ddCompliance = formApi4Cap4.getFormByFormCode(Constants.ddCompliance);
                            String no = dataMaster.getFieldValue(formBean.getFieldBeanByDisplay("经销商ID").getName()).toString();
                            Map param = new HashMap();
                            param.put("name", no);
                            Map<String, Object> result = qiangsDao.findByNo(ddCompliance, param);
                            log.info("qiangsDao.findByNo return :" + result);
                            
                            if (result != null) {
                                String dealerContext = MapUtils.getString(result, ddCompliance.getFieldBeanByDisplay("经销商解释").getName());
                                param.put("dealerContext", dealerContext);
                                log.info("show dealerContext : " + dealerContext + ";no:" + no);
                                if (qiangsDao.isCompliance(ddCompliance, param)) {
                                    dataMaster.addFieldValue(formBean.getFieldBeanByDisplay("合规状态").getName(), "1");
                                    lastUpdate = true;
                                } else {
                                    continue;
                                }
                            } else {
                            	dataMaster.addFieldValue(formBean.getFieldBeanByDisplay("合规状态").getName(), "1");
                                lastUpdate = true;
                            }

                        } else if (Strings.isEmpty(state)) {
                            /******承诺函 节点校验*******/
                            Date createDate = ParamUtil.getDate(params, "receive_time", null, "yyyy-MM-dd HH:mm:ss", false);
                            GregorianCalendar calendar = new GregorianCalendar();
                            calendar.setTime(createDate);
                            int year = calendar.get(1);
                            Map param = new HashMap();
                            param.put("name", name);
                            param.put("year", year);
                            Date date = qiangsDao.validateLetterState(letterBean, param);
                            if (date == null) {
                                continue;
                            }
                            if (null != formBean.getFieldBeanByDisplay("承诺函签署时间")) {
                            	dataMaster.addFieldValue(formBean.getFieldBeanByDisplay("承诺函签署时间").getName(), date);

                            	String flowNo = dataMaster.getFieldValue(formBean.getFieldBeanByDisplay("经销商ID").getName()).toString();
                            	FormBean stateBean = formApi4Cap4.getFormByFormCode(Constants.DDDState);
                            	FlipInfo fli = new FlipInfo(1, 20);
                                Map<String, Object> where = new HashMap<String, Object>();
                                where.put(stateBean.getFieldBeanByDisplay("Id").getName(), flowNo);//经销商ID
                                List<FormDataMasterBean> list = formApi4Cap4.findMasterDataList(fli, stateBean.getId(), null, where);
                                if(CollectionUtils.isNotEmpty(list)){
                                	FormDataMasterBean stateFormDataMaster =list.get(0);
                                	stateFormDataMaster.addFieldValue(stateBean.getFieldBeanByDisplay("FlowState").getName(), "S016");
                                	stateFormDataMaster.addFieldValue(stateBean.getFieldBeanByDisplay("IsCurrent").getName(), "1");
                                	stateFormDataMaster.addFieldValue(stateBean.getFieldBeanByDisplay("CreateDate").getName(), date);
                                	formApi4Cap4.saveOrUpdateFormData(stateFormDataMaster, stateBean.getId(), true);
                                }
                            }
                            dataMaster.addFieldValue(formBean.getFieldBeanByDisplay("承诺函状态").getName(), "1");
                            lastUpdate = true;
                        } else {
                            /******sms节点状态校验*******/
                        	FormFieldBean field = formBean.getFieldBeanByDisplay("经销商等级");
            				Object toObj = dataMaster.getFieldValue(field.getName());
            				Object[] displayObj = field .getDisplayValue(toObj, true);
            				String level = displayObj[1].toString();
                        	String abridge = dataMaster.getFieldValue(formBean.getFieldBeanByDisplay("产品线缩写").getName()).toString();
                            Map param = new HashMap();
                            param.put("name", name);
                            param.put("bu", abridge);
                            param.put("status", "合作中");
                            List<Map> simsList = qiangsDao.checkAgentInSims(ddBean, param);
                            boolean isConitnue = false;
                            for (Map<String, Object> agent : simsList) {
                            	log.info("##强生客开:  abridge="+abridge+"--------------------bu=" + MapUtils.getString(agent, "bu"));
            					if(abridge.equals(MapUtils.getString(agent, "bu"))){
            						if("一级经销商".equals(level)){
            							if("一级".equals(MapUtils.getString(agent, "level"))
            									&& "经销商".equals(MapUtils.getString(agent, "clname"))){//
            								isConitnue = true;
            							}
            						} else if("非一级经销商".equals(level)){
            							if(!"一级".equals(MapUtils.getString(agent, "level"))
            									&& "经销商".equals(MapUtils.getString(agent, "clname"))){
            								isConitnue = true;
            							}
            						} else {
            							if(!"经销商".equals(MapUtils.getString(agent, "clname"))){
            								isConitnue = true;
            							}
            						}
            					}
            				}
                            if (!isConitnue) {
                                continue;
                            }
                        }
                    } else if (renewBean.getId().equals(formId)) {
                        dataMaster = formApi4Cap4.getDataMasterBeanById(masterId, renewBean, null);
                        String state = dataMaster.getFieldValue(renewBean.getFieldBeanByDisplay("发起状态").getName()) == null
                                ? "" : dataMaster.getFieldValue(renewBean.getFieldBeanByDisplay("发起状态").getName()).toString();
                        if (Strings.isEmpty(state)) {
                            content = renewSendValidt(renewBean, dataMaster);
                            if ("error".equals(content)) {
                                continue;
                            }
                            dataMaster.addFieldValue(renewBean.getFieldBeanByDisplay("发起状态").getName(), "1");
                            firstUpdate = true;
                        } else {
                            FormBean ddCompliance = formApi4Cap4.getFormByFormCode(Constants.ddCompliance);
                            String no = dataMaster.getFieldValue(renewBean.getFieldBeanByDisplay("经销商ID").getName()).toString();
                            Map param = new HashMap();
                            param.put("name", no);
                            Map<String, Object> result = qiangsDao.findByNo(ddCompliance, param);
                            log.info("qiangsDao.findByNo return :" + result);
                            if (result != null) {
                                String dealerContext = MapUtils.getString(result, ddCompliance.getFieldBeanByDisplay("经销商解释").getName());
                                param.put("dealerContext", dealerContext);
                                log.info("show dealerContext : " + dealerContext + ";no:" + no);
                                if (!qiangsDao.isCompliance(ddCompliance, param)) {
                                    continue;
                                }
                            }
                        }
                    }

                    if (RestUtil.getInstence().authenticate()) {
                        Map res = new HashMap();
                        res.put("affairId", affairId);
                        res.put("memberid", member.getId());//当前处理人ID
                        if (null == content) {
                            res.put("comment", "自动处理");//处理意见
                            res.put("attitude", "0");//态度：1同意，2不同意，0已阅
                        } else {
                            res.put("comment", content);//处理意见
                            res.put("attitude", "2");//态度：1同意，2不同意，0已阅
                        }
                        try {
                            if (firstUpdate) {
                                formApi4Cap4.saveOrUpdateFormData(dataMaster, formId, true);
                                Thread.sleep(5*10000);
                            }
                            content = RestUtil.getInstence().getClient()
                                    .post("affair/finishaffair", res, String.class);
                            if ("true".equals(content)) {
                                log.info("##强生客开: 自动处理 提交rest节点处理****end");
                                if (lastUpdate) {
                                    formApi4Cap4.saveOrUpdateFormData(dataMaster, formId, true);
                                }
                            }
                        } catch (Exception e1) {
                            // TODO Auto-generated catch block
                            log.error("##强生客开: ", e1);
                        }
                        log.info("##强生客开: 自动处理 《" + subject + "》****end");
                    }
                } catch (Exception e) {
                    log.error("##强生客开: ", e);
                }
            }
        } catch (Exception e1) {
            // TODO Auto-generated catch block
            log.error("##强生客开: ", e1);
        }
    }

    @Override
    @AjaxAccess
    public String resendMail(String userIds) {
        String ret = null;
        V3xOrgDepartment dept = baseQiangsDao.getDeptByCode(Constants.DEFAULT_ACCOUNT_ID, "code",
                Constants.DD_DEFAULTCODE);
        for (String user : userIds.split(",")) {
            String id = user.split("\\|")[1];
            try {
                V3xOrgMember member = orgManager.getMemberById(Long.valueOf(id));
                if (!member.getOrgDepartmentId().equals(dept.getId())) {
                    continue;
                }
                String newPwd = RandomCode.getStringPwd(8);
                member.getV3xOrgPrincipal().setPassword(newPwd);
                orgManagerDirect.updateMember(member);

                FormBean formBean = formApi4Cap4.getFormByFormCode(Constants.ddApplyCode);
                Long ddId = qiangsDao.getDDAttacheByAgent(formBean, member.getId());
                if (null == ddId) {
                    formBean = formApi4Cap4.getFormByFormCode(Constants.ddRenew);
                    ddId = qiangsDao.getDDAttacheByAgent(formBean, member.getId());
                    if (null == ddId) {
                        continue;
                    }
                }
                V3xOrgMember ddMember = orgManager.getMemberById(ddId);
                String ddMail = ddMember.getName() + "	" + ddMember.getOfficeNum()
                        + "	" + ddMember.getEmailAddress();

                if (sendMail(null, ddMail, null, member)) {
                    if (Strings.isBlank(ret)) {
                        ret = "经销商：  " + member.getName();
                    } else {
                        ret += "、" + member.getName();
                    }
                }
            } catch (NumberFormatException e) {
                // TODO Auto-generated catch block
                log.error("##强生客开: ", e);
            } catch (BusinessException e) {
                // TODO Auto-generated catch block
                log.error("##强生客开: ", e);
            }
        }
        if (Strings.isNotBlank(ret)) {
            return ret + "	重置密码并推送邮件成功!";
        }
        return null;
    }

    @Override
    public boolean sendMail(List<String> list, String ddMail, Date endDate, V3xOrgMember member) throws BusinessException {
        String date = DateUtil.format(new Date(), "yyyy年MM月dd日");
        String http = SystemEnvironment.getInternetSiteURL();

        Map map = new HashMap();
        map.put("agentName", member.getName());
        map.put("loginName", member.getLoginName());
        map.put("address", http);
        map.put("date", date);
        map.put("ddMail", ddMail);

        //发送邮件
        boolean one = false;
        boolean two = false;
        if (null != list) {
        	String path = null;
        	String loginMail = null;
        	if(endDate == null){
        		path = "dd" + File.separator + "loginMail.ftl";
        		loginMail = kkFlowManager.fltTemplateIntoString(path, map);
        	} else {
        		map.put("stateDate", DateUtil.format(endDate, "yyyy年MM月dd日"));
        		Calendar calendar = Calendar.getInstance();
        		calendar.setTime(endDate);
        		calendar.add(Calendar.YEAR, 3);
        		map.put("endDate", DateUtil.format(calendar.getTime(), "yyyy年MM月dd日"));
        		path = "dd" + File.separator + "renewLoginMail.ftl";
        		loginMail = kkFlowManager.fltTemplateIntoString(path, map);
        	}
            path = "dd" + File.separator + "passwordMail.ftl";
            map.put("password", member.getV3xOrgPrincipal().getPassword());
            String passwordMail = kkFlowManager.fltTemplateIntoString(path, map);

            one = messageMailManager.sendMessageByMail(list, "【强生经销商/服务商注册申请系统邮件】贵司的经销商注册申请已提交-请尽快在线提交材料",
                    loginMail, new Date());
            log.info("##强生客开: 	推送账号邮件-------------" + one);
            list.clear();
            if (Strings.isNotEmpty(member.getEmailAddress())) {
                for (String jxs : member.getEmailAddress().split(";")) {
                    if (Strings.isNotEmpty(jxs)) {
                        list.add(jxs);
                    }
                }
            }
            two = messageMailManager.sendMessageByMail(list, "【强生经销商/服务商注册申请系统邮件】贵司的经销商注册申请已提交-账户密码",
                    passwordMail, new Date());
            log.info("mail = " + list);
            log.info("##强生客开: 	推送密码邮件-------------" + two);
        } else {
            String path = "dd" + File.separator + "resendMail.ftl";
            map.put("password", member.getV3xOrgPrincipal().getPassword());
            String loginMail = kkFlowManager.fltTemplateIntoString(path, map);

            List lists = new ArrayList();
            if (Strings.isNotEmpty(member.getEmailAddress())) {
                for (String jxs : member.getEmailAddress().split(";")) {
                    if (Strings.isNotEmpty(jxs)) {
                        lists.add(jxs);
                    }
                }
            }
            one = messageMailManager.sendMessageByMail(lists, "【强生BPM系统邮件】贵司的经销商注册申请已提交-账户(密码)",
                    loginMail, new Date());
            log.info("##强生客开: 	管理员重发邮件-------------" + one);
            two = true;
        }
        if (one && two) {
            return true;
        }
        return false;
    }

    @Override
    public Map<Long, FormDataMasterBean> findRelationKeyMember(FormBean formBean, FormDataMasterBean formDataMasterBean) throws BusinessException, SQLException {
        Map<Long, FormDataMasterBean> param = new HashMap<Long, FormDataMasterBean>();
        List<Long> list = new ArrayList<Long>();
        FormBean keyBean = formApi4Cap4.getFormByFormCode(Constants.keyMemberCode);

        List<CAPFormRelationRecord> relationList = cap4FormRelationRecordDAO.selectRecordByFormMasterDataId(formDataMasterBean.getId());
        for (FormTableBean subTable : formBean.getTableList()) {
            if (subTable.getDisplay().contains("关键人员简历")) {
                List<FormDataSubBean> formDataSubBean = formDataMasterBean.getSubData(subTable.getTableName());
                for (FormDataSubBean subDataBean : formDataSubBean) {
                    for (CAPFormRelationRecord relation : relationList) {
                        if (subDataBean.getId().equals(relation.getFromSubdataId())) {
                            list.add(relation.getToMasterDataId());
                            break;
                        }
                    }
                }
                break;
            }
        }
        if (CollectionUtils.isNotEmpty(list)) {
            FlipInfo flip = new FlipInfo(1, 500);
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("id", list);
            List<FormDataMasterBean> relatList = formApi4Cap4.findMasterDataList(flip, keyBean.getId(), null, map);
            for (FormDataMasterBean dataMaster : relatList) {
                for (CAPFormRelationRecord relation : relationList) {
                    if (dataMaster.getId().equals(relation.getToMasterDataId())) {
                        param.put(relation.getFromSubdataId(), dataMaster);
                        break;
                    }
                }
            }
        }
        return param;
    }

    @Override
    public String renewSendValidt(FormBean formBean, FormDataMasterBean formDataMasterBean) {
        try {
            //DD经销商审批表发起前校验
            Map param = new HashMap();
            param.put("name", getString(formDataMasterBean, formBean, "经销商名称"));
            param.put("masterId", formDataMasterBean.getId());
            boolean notIn = qiangsDao.checkAgentNotInFlow(formBean, param);
            if (notIn) {
                return "流程中存在同名的经销商,不能发起!";
            }
            param.remove("masterId");
            Date create = qiangsDao.getRecentMonth(formBean, param);
            Calendar cal = Calendar.getInstance();
            cal.add(Calendar.MONTH, -12);
            if (create != null) {
                if (create.after(cal.getTime())) {
                    return "12月内完成renew的经销商，不能重复触发renew流程!";
                }
            }
        } catch (Exception e) {
            log.error("##强生客开: ", e);
            return "error";
        }
//		log.info("##强生客开: DD renew流程发起校验******************");

        for (FormTableBean subTable : formBean.getTableList()) {
            if (subTable.getDisplay().contains("关键人员简历")) {
                formDataMasterBean.getSubData(subTable.getTableName()).remove(0);
            }
        }
        String companyName = getString(formDataMasterBean, formBean, "经销商名称");
        try {
            // 根据经销商名称查询启信宝关键人员并插入底表
            kkqxbManager.saveEmployees(companyName, formBean, formDataMasterBean);
        } catch (Exception e) {
            log.error("##强生客开: ", e);
            return "error";
        }
//		log.info("##强生客开: DD renew流程 插入企信宝关键人员******************");
        try {
            // 插入默认关键人员到底表并将数据ID挂载到表单上
            kkqxbManager.saveDefaultEmployees(companyName, formBean, formDataMasterBean);
        } catch (Exception e) {
            log.error("##强生客开: ", e);
            return "error";
        }
//		log.info("##强生客开: DD renew流程 插入默认关键人员******************");
        try {
            //DD专员排班人员分配
            kkDistributor.HccPaiban(formBean, formDataMasterBean);
        } catch (Exception e) {
            log.error("##强生客开: ", e);
            return "error";
        }
//		log.info("##强生客开: DD renew流程 DD专员排班******************");
        try {
            //发起前校验通过后创建DD经销商账号
            kkDistributor.CreateDistributor(formBean, formDataMasterBean);
        } catch (Exception e) {
            log.error("##强生客开: ", e);
            return "error";
        }
//		log.info("##强生客开: DD renew流程 创建账号、推送邮件******************");
        return null;
    }

    private String urlEncoder(String url){
    	if(Strings.isNotEmpty(url)){
	    	int index = url.lastIndexOf("/")+1;
	    	String start = url.substring(0, index);
	    	try {
				url = URLEncoder.encode(url.substring(index), "utf-8");
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				log.error("##强生客开: ", e);
			}
			return start+url;
    	} else {
    		return "";
    	}
    }
    
    @Override
    public void findReport() {
        try {
            FormBean formBean = formApi4Cap4.getFormByFormCode(Constants.hehe);
            FlipInfo fli = new FlipInfo(1, 200);
            Map<String, Object> where = new HashMap<String, Object>();
            where.put(formBean.getFieldBeanByDisplay("URL").getName(), "");
            List<FormDataMasterBean> list = formApi4Cap4.findMasterDataList(fli, formBean.getId(), null, where);
            boolean isLoop = true;
            while (isLoop) {
                if (fli.getPage() != 1) {
                    list = formApi4Cap4.findMasterDataList(fli, formBean.getId(), null, where);
                    if (CollectionUtils.isEmpty(list) || list.size() <= 199) {
                        isLoop = false;
                    }
                }
                fli.setPage(fli.getPage() + 1);

                for (FormDataMasterBean dataMasterBean : list) {
                    String id = dataMasterBean.getFieldValue(formBean.getFieldBeanByDisplay("报告ID").getName()).toString();
                    try {
                        String agentName = getString(dataMasterBean, formBean, "经销商名称");
                        Map res = HeheHttpUtil.getReportStatusById(agentName, id);
                        if (res != null) {
                            dataMasterBean.addFieldValue(formBean.getFieldBeanByDisplay("URL").getName(),
                            		urlEncoder(ParamUtil.getString(res, "pdfUrl", "")));
                            dataMasterBean.addFieldValue(formBean.getFieldBeanByDisplay("报告生成时间").getName(),
                                    DateUtil.currentDate());
                            formApi4Cap4.saveOrUpdateFormData(dataMasterBean, formBean.getId(), true);

                            String date = DateUtil.format(new Date(), "yyyy年MM月dd日");
                            String http = SystemEnvironment.getInternetSiteURL();
                            Map map = new HashMap();
                            map.put("agentName", dataMasterBean.getFieldValue(formBean.getFieldBeanByDisplay("经销商名称").getName()).toString());
                            map.put("reportAddress", urlEncoder(ParamUtil.getString(res, "pdfUrl", "")));
                            map.put("address", http);
                            map.put("date", date);

                            String path = "dd" + File.separator + "reportMail.ftl";
                            String reportMail = kkFlowManager.fltTemplateIntoString(path, map);
                            Long memberId = Long.valueOf(dataMasterBean.getFieldValue(formBean.getFieldBeanByDisplay("节点处理人").getName()).toString());
                            V3xOrgMember member = orgManager.getMemberById(memberId);
                            List mails = new ArrayList<>();
                            if (Strings.isNotEmpty(member.getEmailAddress())) {
                                for (String jxs : member.getEmailAddress().split(";")) {
                                    if (Strings.isNotEmpty(jxs)) {
                                        mails.add(jxs);
                                    }
                                }
                            }
                            boolean send = messageMailManager.sendMessageByMail(mails, "【强生经销商/服务商注册申请系统邮件】企业报告已生成",
                                    reportMail, new Date());
                            log.info("##强生客开: 	推送生成企业报告邮件-------------" + send);
                        }
                    } catch (Exception e) {
                        log.error("##强生客开: ", e);
                    }
                }
            }
        } catch (Exception e) {
            log.error("##强生客开: ", e);
        }
    }

    private String getString(FormDataMasterBean formDataMasterBean, FormBean formBean, String display) {
        try {
            return formDataMasterBean.getFieldValue(formBean.getFieldBeanByDisplay(display).getName()).toString();
        } catch (Exception e) {
            return "";
        }
    }
}
